package com.mac.bluetoothbt.feature;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.ConstraintSet;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.*;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Text;

import java.math.BigDecimal;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.xml.datatype.Duration;

import static android.graphics.Color.RED;

/**
 * @author wyh
 */
public class Main2Activity extends Activity {
    public static final String DEVICESTATE = "devicestate";
    BroadcastReceiver broadcastReceiver;
    DeviceEntity deviceEntity = new DeviceEntity();
    private boolean isMute = false;
    private boolean isBlink = false;
    private int width6div;
    private int screanHeight;
    private ConstraintLayout activity2layout;
    private List<View> cyViewList = new ArrayList<>();

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2_flat);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        broadcastReceiver = new Acrivity2BroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Actions.ACTION_DATA_UPDATE);
        filter.addAction(Actions.ACTION_BLE_DISCONNECT);
        filter.addAction(Actions.ACTION_REMAINTIME);
        filter.addAction(Actions.ACTION_BACK_DATA);
        filter.addAction(Actions.ACTION_WRITE_SUCCESS);
        registerReceiver(broadcastReceiver, filter);


        activity2layout = findViewById(R.id.innerconstraint);
        getWindowWidthAndHeight();

        //初始化
        cyViewList.add(findViewById(R.id.gastank0));
        cyViewList.add(findViewById(R.id.gastank1));
        cyViewList.add(findViewById(R.id.gastank2));
        cyViewList.add(findViewById(R.id.gastank3));
        cyViewList.add(findViewById(R.id.gastank4));
        cyViewList.add(findViewById(R.id.gastank5));
        for (View view :
                cyViewList) {
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.width = width6div;
            view.setLayoutParams(layoutParams);
        }
    }

    private void getWindowWidthAndHeight() {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        int screanWidth = displayMetrics.widthPixels;
        width6div = screanWidth / 6;
        screanHeight = displayMetrics.heightPixels;
    }

    @Override
    protected void onResume() {
        getRemain();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            startActivity(new Intent(Intent.ACTION_MAIN).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addCategory(Intent.CATEGORY_HOME));
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void getRemain() {
        sendBroadcast(new Intent(Actions.ACTION_STOPREAD));
        if (App.timeReadTime == 0) {
            FrameUtil.readremaintime6(getApplicationContext());
        }

        //延迟执行
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.schedule(new Runnable() {
            @Override
            public void run() {
                sendBroadcast(new Intent(Actions.ACTION_STARTREAD));
            }
        }, 500, TimeUnit.MILLISECONDS);
    }

    private Drawable getBackGround(int index) {
        switch (index) {
            case 0:
                return getDrawable(R.mipmap.half);
            case 1:
                return getDrawable(R.mipmap.empty);
            case 2:
                return getDrawable(R.mipmap.full);
            default:
                return getDrawable(R.mipmap.empty);
        }
    }

    private void setAcell(TextView data, TextView dataName, TextView state, Sensor sensor) {
        data.setText(String.format(Locale.PRC, "%f", (sensor.getDisplayVal())));
        dataName.setText(sensor.getGasClassString());
        state.setText(sensor.getStateString());
        if (sensor.getState() == 0) {
            data.setTextColor(Color.GREEN);
            state.setTextColor(Color.GREEN);
        } else {
            data.setTextColor(RED);
            state.setTextColor(RED);
        }
    }

    /**
     * 静音键onClick
     *
     * @param view View对象
     */
    public void soundSwitchClicked(View view) {
        if (isMute) {
            FrameUtil.setSendSoundOn(getApplicationContext());
        } else {
            FrameUtil.sendSilent(getApplicationContext());
        }
    }

    /**
     * 设置键onClick
     *
     * @param view View对象
     */
    public void onSettingClicked(View view) {
        if (((App) getApplication()).getDeviceEntity() == null) {
            Toast.makeText(this, "没有接收到设备数据，无法设置", Toast.LENGTH_LONG).show();
            return;
        }
        sendBroadcast(new Intent(Actions.ACTION_STOPREAD));
        startActivity(new Intent().setClass(this, SettingActivity.class)
                .putExtra(DEVICESTATE, deviceEntity));
    }

    /**
     * 测试键onClick
     *
     * @param view View对象
     */
    public void testClicked(View view) {
        FrameUtil.sendTest(getApplicationContext());
    }


    private static final int[] IDS = {R.id.cylinderview_1, R.id.cylinderview_2, R.id.cylinderview_3,
            R.id.cylinderview_4, R.id.cylinderview_5, R.id.cylinderview_6};

    private void updateOneTurnFlat(byte[] serialData, int length) {
        int frame = deviceEntity.setRegisters(serialData, length);
        if (frame == 1) {
            ((App) getApplication()).setDeviceEntity(new DeviceEntity(deviceEntity));
        }

        List<Sensor> sensors = deviceEntity.getSensors();
        int channelAmount = deviceEntity.getChannelAmount();
        //重新计算布局
        if (channelAmount != 0) {
//            for (View view :
//                    cyViewList) {
//                view.setVisibility(View.GONE);
//            }

            List<View> visibleViewList = new ArrayList<>();
            for (int i = 0; i < channelAmount; i++) {
                Sensor currSensor = sensors.get(i);
//                if (21 == currSensor.getGasIndex()) {
//                    continue;
//                }
                cyViewList.get(i).setVisibility(View.VISIBLE);
                visibleViewList.add(cyViewList.get(i));
            }

            ConstraintSet constraintSet = new ConstraintSet();
            constraintSet.clone(activity2layout);
            for (int i = 0; i < visibleViewList.size(); i++) {
                //上下连接容器上下
                constraintSet.connect(visibleViewList.get(i).getId(), ConstraintSet.BOTTOM,
                        activity2layout.getId(), ConstraintSet.BOTTOM);
                constraintSet.connect(visibleViewList.get(i).getId(), ConstraintSet.TOP,
                        activity2layout.getId(), ConstraintSet.TOP);

                if (i == 0) {
                    //第一个连接容器左
                    constraintSet.connect(visibleViewList.get(i).getId(), ConstraintSet.LEFT,
                            activity2layout.getId(), ConstraintSet.LEFT);
                } else {
                    //连接先驱右
                    constraintSet.connect(visibleViewList.get(i).getId(), ConstraintSet.LEFT,
                            visibleViewList.get(i - 1).getId(), ConstraintSet.RIGHT);
                }

                if (i == visibleViewList.size() - 1) {
                    //最后一个连接容器右
                    constraintSet.connect(visibleViewList.get(i).getId(), ConstraintSet.RIGHT,
                            activity2layout.getId(), ConstraintSet.RIGHT);
                } else {
                    //连接后继者左
                    constraintSet.connect(visibleViewList.get(i).getId(), ConstraintSet.RIGHT,
                            visibleViewList.get(i + 1).getId(), ConstraintSet.LEFT);
                }

            }
            constraintSet.applyTo(activity2layout);
        }
        for (int i = 0; i < deviceEntity.getChannelAmount() || i < 6; i++) {
            try {
                if (21 == (sensors.get(i).getGasIndex())) {
                    cyViewList.get(i).setVisibility(View.GONE);
                    fill(i);
                } else {
                    fill(sensors, i);
                }
            } catch (InvalidParameterException e) {
                e.printStackTrace();
            }
        }

        //全部未使用
        if (deviceEntity.allNotused()) {
            for (View view : cyViewList) {
                view.setVisibility(View.VISIBLE);
            }
        }


        //更新蓝牙和静音状态
        updateBleConnectStatusPicture();
        updateMuteStatusPicture();

        if (isBlink) {
            blink();
        }
    }


    @ColorInt
    public static final int GREEN = 0xFF006400;

    private void fill (int i) {
        View currView = cyViewList.get(i);
        TextView gasNameChemistry = currView.findViewById(R.id.textView12);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            gasNameChemistry.setText(Html.fromHtml(FrameUtil.getAbb(21),
                    Html.FROM_HTML_MODE_LEGACY));
        } else {
            gasNameChemistry.setText(Html.fromHtml(FrameUtil.getAbb(21)));
        }
        gasNameChemistry.setBackgroundResource(FrameUtil.getGasColorDrawableId(21));

        TextView gasNameChinese = currView.findViewById(R.id.textView13);
        gasNameChinese.setText(FrameUtil.getGas(21));

        BigDecimal dispVal = new BigDecimal("0");
        TextView gasPresureVal = currView.findViewById(R.id.gastankvalue);
        gasPresureVal.setText(dispVal.setScale(2, BigDecimal.ROUND_DOWN).toPlainString());
        gasPresureVal.setTextColor(GREEN);

        TextView gasPresureUnit = currView.findViewById(R.id.gastankvalueunit);
        gasPresureUnit.setText(FrameUtil.getUnit(0));

        TextView gasStatus = currView.findViewById(R.id.abnormal);
        gasStatus.setText(FrameUtil.getState(3));
        gasStatus.setTextColor(GREEN);

        ImageView gasStatusPic = currView.findViewById(R.id.imageView);
        gasStatusPic.setBackgroundResource(R.drawable.state_red);
    }

    private void fill(@NotNull List<Sensor> sensors, int i) {
        //填充罐体
        Sensor currSensor = sensors.get(i);
        doFill(i, currSensor);
    }

    private void doFill(int i, Sensor currSensor) {
        View currView = cyViewList.get(i);
        TextView gasNameChemistry = currView.findViewById(R.id.textView12);
        TextView gasNameChinese = currView.findViewById(R.id.textView13);
        TextView gasPresureVal = currView.findViewById(R.id.gastankvalue);
        TextView gasPresureUnit = currView.findViewById(R.id.gastankvalueunit);
        TextView gasStatus = currView.findViewById(R.id.abnormal);
        ImageView gasStatusPic = currView.findViewById(R.id.imageView);
        BigDecimal dispVal = new BigDecimal(((Number)currSensor.getDisplayVal()).toString());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            gasNameChemistry.setText(Html.fromHtml(FrameUtil.getAbb(currSensor.getGasIndex()),
                    Html.FROM_HTML_MODE_LEGACY));
        } else {
            gasNameChemistry.setText(Html.fromHtml(FrameUtil.getAbb(currSensor.getGasIndex())));
        }

        gasNameChemistry.setBackgroundResource(FrameUtil.getGasColorDrawableId(currSensor.getGasIndex()));
        gasNameChinese.setText(currSensor.getGasClassString());
        gasPresureVal.setText(dispVal.setScale(2, BigDecimal.ROUND_DOWN).toPlainString());
        gasPresureUnit.setText(FrameUtil.getUnit(currSensor.getMeasureRangeIndex()));

        int status = currSensor.getState();
        if (FrameUtil.SensorStatus.NORMAL.ordinal() == status) {
            gasStatus.setText(FrameUtil.getState(status));
            gasStatus.setTextColor(GREEN);
            gasPresureVal.setTextColor(GREEN);
            gasStatusPic.setBackgroundResource(R.drawable.state_green);
        } else {
            gasStatus.setText(FrameUtil.getState(status));
            gasStatus.setTextColor(RED);
            gasPresureVal.setTextColor(RED);
            gasStatusPic.setBackgroundResource(R.drawable.state_red);
        }
        updateMuteStatusPicture();
    }

    private static boolean state = false;
    private static int count = 0;

    void blink() {
        TextView shadow = findViewById(R.id.shadow), needmaintain = findViewById(R.id.needmaintain);
        shadow.setVisibility(state ? View.VISIBLE : View.GONE);
        needmaintain.setVisibility(View.VISIBLE);

        if (state) {
            //黑屏
            for (View view :
                    cyViewList) {
                view.setVisibility(View.INVISIBLE);
            }
        }

        if (count == 0) {
            state = !state;
        }
        if (count == 1) {

        }
        if (count == 2) {
            count = -1;
        }
        count++;
    }

    /**
     * 读到密码
     *
     * @param serialdata 密码数据
     */
    private void passwordGot(byte[] serialdata) {
        String password = new String(serialdata, 4, serialdata[3]);
        sendBroadcast(new Intent(Actions.ACTION_PASSWORDGOT).putExtra("password", password));
    }

    private class Acrivity2BroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == null) {
                return;
            }
            switch (intent.getAction()) {
                case Actions.ACTION_DATA_UPDATE:
                    byte[] serialdata = intent.getByteArrayExtra("data");
                    switch (serialdata[1]) {
                        case 0x03:
                            int length = intent.getIntExtra("length", 0);
                            updateOneTurnFlat(serialdata, length);
                            break;
                        case 0x41:
                            passwordGot(serialdata);
                            break;
                        default:
                            break;
                    }
                    updateBleConnectStatusPicture();
                    break;
                case Actions.ACTION_BLE_DISCONNECT:
                    updateBleConnectStatusPicture();
                    break;
                case Actions.ACTION_REMAINTIME:
                    int remain = intent.getIntExtra("data", 0);
                    if (remain == 0) {
                        isBlink = true;
                    }
                    break;
                case Actions.ACTION_BACK_DATA:
                    byte[] backdata = intent.getByteArrayExtra("data");
                    if (backdata != null) {
                        if (Arrays.equals(FrameUtil.SEND_SOUND_OFF, backdata)) {
                            isMute = true;
                        } else if (Arrays.equals(FrameUtil.SEND_SOUND_OFF, backdata)) {
                            isMute = false;
                        }
                    }
                    updateMuteStatusPicture();
                    break;
                case Actions.ACTION_WRITE_SUCCESS:
                    Toast.makeText(getApplicationContext(), "设置成功", Toast.LENGTH_LONG).show();
                    break;
                case Actions.ACTION_WRITE_FAIL:
                    Toast.makeText(getApplicationContext(), "设置失败", Toast.LENGTH_LONG).show();
                default:
                    break;
            }
        }


    }

    private void updateBleConnectStatusPicture() {
        //更新蓝牙状态
        ImageButton imageButton = findViewById(R.id.bluetooth_btn);
        if (FastBleService.isBtConnected) {
            imageButton.setBackgroundResource(R.drawable.icon_bluetooth_linked);
        } else {
            imageButton.setBackgroundResource(R.drawable.icon_bluetooth_disconnected);
        }
    }

    private void updateMuteStatusPicture() {
        //更新静音状态
        ImageButton imageButton = findViewById(R.id.mute_btn);
        if (isMute) {
            imageButton.setBackgroundResource(R.drawable.icon_muted);
        } else {
            imageButton.setBackgroundResource(R.drawable.icon_notmute);
        }
    }
}
